import React from "react";

import { Row, Col, Table, message } from 'antd';
import { connect } from 'dva';

// import { setLineChart } from './chart'
import { SingleBar } from '@/components/Chart/Bar'
import { checkInit, splitObject } from '@/utils/util';
import SearchForm from './components/SearchForm';
import { exportExcl } from '@/utils/xlsx';
import XLSX from "xlsx";

interface IProps {
  dispatch?: Function,
  children?: React.ReactNode,
  loading: boolean,
  group?: Array<any>,
  role?: Array<any>,
  list: {
    data: Array<any>,
    dataCnt: number
  },
  listAll: {
    data: Array<any>,
    dataCnt: number
  }
}

let setPageNum = 1;

@connect(({ analyse_person, loading }) => ({
  role: analyse_person.count ? analyse_person.count.role : null,
  group: analyse_person.count ? analyse_person.count.group : null,
  list: analyse_person.list,
  listAll: analyse_person.listAll,
  loading: loading.effects['analyse_person/queryPage'],
}))
class Basiccolumn extends React.PureComponent<IProps> {

  state = {
    current: 1,
    sortType: '',
    isChangePage: false
  };

  handleChange = (pagination, filters, sorter) => {
    if(!sorter.order) {
      message.loading('', 0.6);
      this.setState({
        sortType: ''
      });
      this.queryData({
        pageNum: setPageNum,
        pageSize: 10
      });
      return;
    }
    let type = '';
    if(sorter.order === 'ascend') {
      // 升序
      switch(sorter.columnKey) {
        case '4': // 报警处理率
          type = 'handleRate';
          break;
        case '5': // 任务完成率
          type = 'finishRate';
          break;
        case '6': // 值班率
          type = 'dutyRate';
          break;
      }
    }
    if(sorter.order === 'descend') {
      // 降序
      switch(sorter.columnKey) {
        case '4': // 报警处理率
          type = '-handleRate';
          break;
        case '5': // 任务完成率
          type = '-finishRate';
          break;
        case '6': // 值班率
          type = '-dutyRate';
          break;
      }
    }
    this.setState({
      sortType: type
    });
    this.queryData({
      pageNum: setPageNum,
      pageSize: 10,
      sort: type
    });
  };

  queryData = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'analyse_person/queryPage',
      payload: params,
    });
  };

  initCurrent = () => {
    this.setState({
      current: 1
    })
  };

  handleExport = e => {
    const { dispatch } = this.props;

    dispatch({ type: 'analyse_person/queryPageAll' }).then(e => {
      const { listAll = {data: []} }  = this.props;
    const { data } = listAll;

    const ans = data && Array.isArray(data) && data.map(item => {
      return {
        '姓名': item.loginName,
        '职位': item.positionName,
        '部门': item.groupName,
        '报警处理率': !isNaN(+item.handleRate) && `${(+item.handleRate * 100).toFixed(2)}%`,
        '任务完成率': !isNaN(+item.finishRate) && `${(+item.finishRate * 100).toFixed(2)}%`,
        '值班率': !isNaN(+item.dutyRate) && `${(+item.dutyRate * 100).toFixed(2)}%`,
        '正常巡逻数': item.positionCount,
        '隐患整改数': item.rectifyCount
      }
    });

    exportExcl({
      XLSX,
      data: ans,
      name: "人员统计",
      fileName: "人员统计"
    })
    })
  };

  componentDidMount = () => {
    const { dispatch } = this.props;
    const hasMsg = message.loading('');
    checkInit();
    this.queryData({
      pageNum: 1,
      pageSize: 10
    });
    dispatch({ type: 'analyse_person/queryCount' }).then(() => {
      const { role = [], group = [] } = this.props;
      const roleArr = splitObject(role);
      const groupArr = splitObject(group);
      if(Array.isArray(roleArr)) {
        SingleBar({
          dataX: roleArr[0],
          dataY: roleArr[1],
          nameX: '角色',
          nameY: '人数',
          ref: this.refs.role,
          title: '角色统计'
        });
      }
      if(Array.isArray(groupArr)) {
        SingleBar({
          dataX: groupArr[0],
          dataY: groupArr[1],
          nameX: '部门',
          nameY: '人数',
          ref: this.refs.group,
          title: '部门统计'
        })
      }
      hasMsg()
    })
  };

  render() {
    const { list = {data: [], dataCnt: 0} }  = this.props;
    const { data, dataCnt } = list;
    const ans = data && Array.isArray(data) ? data.map((item, index) => ({
      key: index,
      loginName: item.loginName,
      positionName: item.positionName ? item.positionName : ' ',
      groupName: item.groupName ? item.groupName : ' ',
      handleRate: item.handleRate || item.handleRate === 0 ? item.handleRate : ' ',
      finishRate: item.finishRate || item.finishRate === 0 ? item.finishRate : ' ',
      dutyRate: item.dutyRate || item.dutyRate === 0 ? item.dutyRate : ' ',
      positionCount: item.positionCount ? item.positionCount : ' ',
      rectifyCount: item.rectifyCount ? item.rectifyCount : ' '
      })
    ) : [];

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showQuickJumper: true,
      pageSize: 10,
      onChange: (current) => {
        setPageNum = current;
        this.setState({
          current,
          isChangePage: true
        });
      },
    };

    const columns: any = [{
      key: '1',
      title: '登录名',
      dataIndex: 'loginName',
    }, {
      key: '2',
      title: '职位',
      dataIndex: 'positionName',
    }, {
      key: '3',
      title: '部门',
      dataIndex: 'groupName',
    }, {
      key: '4',
      title: '报警处理率',
      dataIndex: 'handleRate',
      render: (text) => {
        return !isNaN(+text) ? `${(+text * 100).toFixed(2)}%` : '0%'
      },
      onFilter: () => {},
      sorter: () => {}
    }, {
      key: '5',
      title: '任务完成率',
      dataIndex: 'finishRate',
      render: (text) => {
        return !isNaN(+text) ? `${(+text * 100).toFixed(2)}%` : '0%'
      },
      onFilter: () => {},
      sorter: () => {}
    }, {
      key: '6',
      title: '值班率',
      dataIndex: 'dutyRate',
      render: (text) => {
        return text ? `${(+text * 100).toFixed(2)}%` : '0%'
      },
      onFilter: () => {},
      sorter: () => {}
    }, {
      key: '7',
      title: '正常巡逻数',
      dataIndex: 'positionCount',
    }, {
      key: '8',
      title: '隐患整改数',
      dataIndex: 'rectifyCount',
    }];

    return (
      <>
        <Row style={{ margin: '25px 30px' }}>
          <Col span={12} style={{height: '300px'}}>
            <section style={{ height: '90%', width: '100%', marginLeft: '1%' }}>
              <div ref='role' style={{ width: '100%', height: '100%' }}></div>
            </section>
          </Col>
          <Col span={12} style={{height: '300px'}}>
            <section style={{ height: '90%', width: '100%', marginLeft: '2%' }}>
              <div ref='group' style={{ width: '100%', height: '100%' }}></div>
            </section>
          </Col>
        </Row>
        <Row>
          <SearchForm current={ this.state.current } initCurrent={this.initCurrent} handleExport={this.handleExport}/>
          <Table
            columns={columns}
            pagination={pagination}
            dataSource={ans}
            bordered
            loading={this.props.loading}
            onChange={this.handleChange}
          />
        </Row>
      </>
    );
  }
}

export default Basiccolumn;
